/**
 *
 */
package com.tc.dispatch.web.schedule.cost;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.directwebremoting.WebContext;
import org.directwebremoting.WebContextFactory;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import com.tc.dispatch.csservice.algorithm.CostAlgorithm;
import com.tc.dispatch.csservice.algorithm.adjust.Adjust;
import com.tc.dispatch.csservice.algorithm.adjust.AveravgeAdjust;
import com.tc.dispatch.csservice.algorithm.calculation.Calclation;
import com.tc.dispatch.csservice.ejb.CSServiceLocal;
import com.tc.dispatch.csservice.exception.CSException;

import com.tc.dispatch.csservice.model.CostEstimateDetail;
import com.tc.dispatch.csservice.model.Product;

import com.tc.dispatch.gsalgorithm.exception.AlgorithmException;
import com.tc.dispatch.gsalgorithm.spec.parse;
import com.tc.dispatch.gsalgorithm.spec.spec;
import com.tc.dispatch.gsalgorithm.spec.specConst;
import com.tc.dispatch.gsservice.action.GSCalcAction;
import com.tc.dispatch.gsservice.basic.common.tcdate;
import com.tc.dispatch.gsservice.ejb.GSServiceLocal;
import com.tc.dispatch.gsservice.exception.GSException;
import com.tc.dispatch.csservice.model.ManuCost;
import com.tc.dispatch.gsservice.model.OrderSumMain;
import com.tc.dispatch.gsservice.model.OtherConstants;
import com.tc.dispatch.gsservice.model.ProcessArea;
import com.tc.dispatch.gsservice.model.ProcessFee;
import com.tc.dispatch.gsservice.model.SsignDensity;
import com.tc.dispatch.csservice.model.ProcsDetail;
import com.tc.dispatch.web.controller.UserState;
import com.tc.dispatch.web.csservice.csHelper;
import com.tc.dispatch.web.gsservice.gsHelper;
import com.tc.dispatch.web.model.CacheSimModel;
import com.tc.dispatch.csservice.model.CombinedOrderSumMainSimilay;
import com.tc.dispatch.csservice.model.component.Component;
import com.tc.dispatch.csservice.filter.ComponentFilter;
import com.tc.dispatch.web.util.DateJsonValueProcessor;
import com.tc.dispatch.web.util.FloatJsonValueProcessor;
import com.tc.dispatch.web.util.WidgtFactory;
import com.tc.dispatch.web.util.cache.CacheManager;
import com.tc.dispatch.web.util.cache.CacheMessage;
import com.tc.dispatch.web.util.cache.CacheShell;
import com.tc.dispatch.web.util.cache.imp.SimpleCacheMessage;
import com.tc.dispatch.web.util.check.CheckValid;

/**
 * @author cajeep
 * 
 */
public class CostEstimate extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public CostEstimate() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	public String getSpecType(String spec) {
		if (spec == null)
			return "";
		else
			return parse.parseSpec(spec).sort();

	}

	public Float calcGrossWeight(String spec, String ssign) {
		GSServiceLocal gss = gsHelper.getGSServiceLocal();
		try {
			List ret = gss.findSsignDensity(" where ssign='" + ssign + "'");
			Float density = new Float(0);
			if (ret.size() > 0)
				density = ((SsignDensity) ret.get(0)).getDensity();

			return new Float(parse.parseSpec(spec).volume()
					* density.floatValue() / 1000 / 1000);
		} catch (GSException gse) {

			System.out.println("GSException is found in calcGrossWeight:"
					+ gse.getMessage());
			return new Float(0);
		}

	}
	public List generateCostMin(Product p, Date date1) {
		CSServiceLocal css = csHelper.getCSServiceLocal();
		GSServiceLocal gss = gsHelper.getGSServiceLocal();

		List ret = new ArrayList();
		CacheManager cm = CacheManager.getInstance();
		CacheShell cs = cm.getCacheShell(cm.SIMILIARY_LIST_CACHE);
		CacheShell osmCs = cm.getCacheShell(cm.MOST_SIM_ORDER_CACHE);
		CacheSimModel csm = (CacheSimModel) cs.getValue(p);
		if (csm.getSimList() == null || csm.getSimList().size() == 0)
			return ret;

		try {
			OrderSumMain osm = (OrderSumMain) osmCs.getValue(p);
			List ossList = gss.findOrderSumSub(" where orderSumId="
					+ osm.getId()+" order by processpos");
			/**
			 * 赋值
			 */
			osm.setSpec(p.getSpec());
			osm.setSsign(p.getSsign());
			osm.setPlate(p.getPlate());
			osm.setProcessScheme(new Integer(p.getScheme()));
			osm.setMonth1(new Integer(tcdate.getMonth(date1)));
			osm.setYear1(new Integer(tcdate.getYear(date1)));
			/**
			 * 先计算一下。
			 */
			List retList = css.CostEstimateAdjust(osm, ossList,
					Calclation.WITHOUT_PEIFANG);
			osm = (OrderSumMain) retList.get(0);
			ossList = (List) retList.get(1);
			
			
			ret.clear();
			for (int i = 1; i <= 5; i++) {
				/**
				 * 调整成品率
				 */
				Adjust adj = new AveravgeAdjust(new Integer(i));
				retList = css.CostEstimateAdjust(osm, ossList, adj, csm
						.getSimList());
				if(retList==null||retList.size()!=2)
					{
						ret.add(new Float(999));
						continue;
					}
				osm = (OrderSumMain) retList.get(0);
				ossList = (List) retList.get(1);
				System.out.println("161");
				osm.setFactory(new Integer(i));
				retList=css.CostEstimateAdjust(osm, ossList, Calclation.YIELD_TYPE);
				if(retList==null||retList.size()!=2)
				{
					ret.add(new Float(999));
					continue;
				}
				osm = (OrderSumMain) retList.get(0);
				ossList = (List) retList.get(1);
				ret.add(osm.getProduct_cost_last());
			}
			return ret;
		}

		catch (Exception ex) {
			System.out
					.println("Exception is found in CostEstimate.generateCostMin:"
							+ ex.getMessage());
			return null;
		}
	}
	
	public List generateCostByOsm(Product p, Date date1, String kaimo, int pos) {
		CSServiceLocal css = csHelper.getCSServiceLocal();
		GSServiceLocal gss = gsHelper.getGSServiceLocal();

		List ret = new ArrayList();
		CacheManager cm = CacheManager.getInstance();
		CacheShell cs = cm.getCacheShell(cm.SIMILIARY_LIST_CACHE);
		CacheShell osmCs = cm.getCacheShell(cm.MOST_SIM_ORDER_CACHE);
		
		
		
		CacheSimModel csm = (CacheSimModel) cs.getValue(p);
		if (csm.getSimList() == null || csm.getSimList().size() == 0)
			return ret ;
		try {
			CombinedOrderSumMainSimilay csms = (CombinedOrderSumMainSimilay) csm
					.getSimList().get(pos);
			OrderSumMain osm = csms.getOsm();
			List ossList = csms.getOssList();
			osmCs.setValue(p, osm);
			/**
			 * 赋值date
			 */
			osm.setSpec(p.getSpec());
			if (p.getFactory() > 0)
				osm.setFactory(new Integer(p.getFactory()));
			osm.setSsign(p.getSsign());
			osm.setPlate(p.getPlate());
			osm.setProcessScheme(new Integer(p.getScheme()));
			osm.setMonth1(new Integer(tcdate.getMonth(date1)));
			osm.setYear1(new Integer(tcdate.getYear(date1)));
			/**
			 * 先计算一下。
			 */
			List retList = css.CostEstimateAdjust(osm, ossList,
					Calclation.WITHOUT_PEIFANG);
			if(retList==null||retList.size()!=2)
				return null;
			osm = (OrderSumMain) retList.get(0);
			ossList = (List) retList.get(1);
			
			
			ret.clear();
			for (int i = 1; i <= 5; i++) {
				/**
				 * 调整成品率
				 */
				Adjust adj = new AveravgeAdjust(new Integer(i));
				retList = css.CostEstimateAdjust(osm, ossList, adj, csm
						.getSimList());
				if(retList==null||retList.size()!=2)
					continue;
				osm = (OrderSumMain) retList.get(0);
				ossList = (List) retList.get(1);
				//
				osm.setFactory(new Integer(i));
				retList=css.CostEstimateAdjust(osm, ossList, Calclation.YIELD_TYPE);
				if(retList==null||retList.size()!=2)
					continue;
				osm = (OrderSumMain) retList.get(0);
				ossList = (List) retList.get(1);
				CostEstimateDetail ced = css.getCostEstimateDetail(osm,
						ossList, new ComponentFilter() {
							public boolean filter(String name, Object value) {
								if (name.equals("ssign_yz")
										|| name.equals("ssign")
										|| name.equals("plate")
										|| name.equals("id")
										|| name.equals("transnum")
										|| name.equals("ordernum")
										|| name.equals("feipin")
										|| name.equals("qiandao_cost")
										|| name.equals("specType")
										|| name.equals("processScheme")
										|| name.equals("houdao_yield")
										|| name.equals("date1")
										|| name.equals("ordercost")
										|| name.equals("lirun")
										|| name.equals("bz")
										|| name.equals("maker")
										|| name.equals("makeDate")
										|| name.equals("type")
										|| name.equals("month1")
										|| name.equals("year1")
										|| name.equals("baozhuangfei"))
									return false;
								else
									return true;

							}

							public boolean subPosition(String name, Object value) {
								if (name.equals("plate"))
									return true;
								else
									return false;
							}

						});

				
				ret.add(ced);
			}
			return ret;
		}

		catch (Exception ex) {
			System.out
					.println("Exception is found in CostEstimate.generateCostByOsm:"
							+ ex.getMessage());
			return null;
		}
	}

	/**
	 * 根据开模规格(外界可以修改的)，来估算产品的各个步骤的成品率。的生成一个cedlist。
	 */
	public List generateCost(Product p, Date date1, String kaimo) {
		CSServiceLocal css = csHelper.getCSServiceLocal();
		GSServiceLocal gss = gsHelper.getGSServiceLocal();

		List ret = new ArrayList();
		CacheManager cm = CacheManager.getInstance();
		CacheShell cs = cm.getCacheShell(cm.SIMILIARY_LIST_CACHE);
		CacheShell osmCs = cm.getCacheShell(cm.MOST_SIM_ORDER_CACHE);
		CacheSimModel csm = (CacheSimModel) cs.getValue(p);
		if (csm.getSimList() == null || csm.getSimList().size() == 0)
			return ret;

		try {
			OrderSumMain osm = (OrderSumMain) osmCs.getValue(p);
			List ossList = gss.findOrderSumSub(" where orderSumId="
					+ osm.getId()+" order by processPos");

			/*
			 * 需要自己人为的调整，将最相似的订单的信息进行替换。
			 */
			osm.setSpec(p.getSpec());
			if (p.getFactory() > 0)
				osm.setFactory(new Integer(p.getFactory()));
			osm.setSsign(p.getSsign());
			osm.setPlate(p.getPlate());
			osm.setProcessScheme(new Integer(p.getScheme()));
			osm.setMonth1(new Integer(tcdate.getMonth(date1)));
			osm.setYear1(new Integer(tcdate.getYear(date1)));

			if (kaimo != null && !(kaimo.trim().length() == 0)
					&& !parse.parseSpec(kaimo).equals(specConst.UnparseSpec))
				osm.setSpec_yz(kaimo);
			/**
			 * 设置之后需要先计算一下毛重啥的。
			 */
			List retList = css.CostEstimateAdjust(osm, ossList,
					Calclation.WITHOUT_PEIFANG);
			osm = (OrderSumMain) retList.get(0);
			ossList = (List) retList.get(1);
			/**
			 * 添加adjust，调整成品率
			 */
			
			ret.clear();
			for (int i = 1; i <= 5; i++) {
				Adjust adj = new AveravgeAdjust(new Integer(i));
				retList = css.CostEstimateAdjust(osm, ossList, adj, csm
						.getSimList());
				if(retList==null||retList.size()!=2)
					continue;
				osm = (OrderSumMain) retList.get(0);
				ossList = (List) retList.get(1);
				/**
				 * 转换为组件的形式进行输出。
				 */
				osm.setFactory(new Integer(i));
				retList=css.CostEstimateAdjust(osm, ossList, Calclation.YIELD_TYPE);
				if(retList==null||retList.size()!=2)
					continue;
				osm = (OrderSumMain) retList.get(0);
				ossList = (List) retList.get(1);
				CostEstimateDetail ced = css.getCostEstimateDetail(osm,
						ossList, new ComponentFilter() {
							public boolean filter(String name, Object value) {
								if (name.equals("ssign_yz")
										|| name.equals("ssign")
										|| name.equals("plate")
										|| name.equals("id")
										|| name.equals("transnum")
										|| name.equals("ordernum")
										|| name.equals("feipin")
										|| name.equals("qiandao_cost")
										|| name.equals("specType")
										|| name.equals("processScheme")
										|| name.equals("houdao_yield")
										|| name.equals("date1")
										|| name.equals("ordercost")
										|| name.equals("lirun")
										|| name.equals("bz")
										|| name.equals("maker")
										|| name.equals("makeDate")
										|| name.equals("type")
										|| name.equals("month1")
										|| name.equals("year1")
										|| name.equals("baozhuangfei"))
									return false;
								else
									return true;

							}

							public boolean subPosition(String name, Object value) {
								if (name.equals("plate"))
									return true;
								else
									return false;
							}

						});
				
				ret.add(ced);
			}
			return ret;
		}

		catch (GSException ex) {
			System.out.println("GSException:" + ex.getMessage());
			return null;
		}

	}

	public boolean refreshCache() {
		try {
			CacheManager cm = CacheManager.getInstance();
			CacheMessage cmess = new SimpleCacheMessage(CacheMessage.REMOVE_ALL);
			cmess.addDestination(cm.getCacheShell(cm.SIMILIARY_LIST_CACHE));
			cmess.addDestination(cm.getCacheShell(cm.MOST_SIM_ORDER_CACHE));
			cm.sendMessage(cmess);
			// cs.removeAll();
			return true;
		} catch (Exception e) {
			System.out
					.println("unexpected exception found in CostEstimate.refreshCache:"
							+ e.getMessage());
			return false;
		}
	}

	/**
	 * The doPost method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to
	 * post.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html; charset=utf-8");
		PrintWriter out = response.getWriter();
		CheckValid rcv = WidgtFactory.getRequestCheckValid(request);
		String action = (String) rcv.checkString("action");
		CSServiceLocal css = csHelper.getCSServiceLocal();
		GSServiceLocal gss = gsHelper.getGSServiceLocal();
		HttpSession sess = request.getSession();

		if (action.equals("getSimiList")) {

			String specType = (String) rcv.checkString("specType", "yuanzhu");
			Integer scheme = (Integer) rcv.checkInteger("scheme");
			String spec = (String) rcv.checkString("spec");
			Integer factory = (Integer) rcv.checkInteger("factory");
			String ssign = (String) rcv.checkString("ssign");
			String plate = (String) rcv.checkString("plate");

			List osmList = new ArrayList();
			try {
				List ret;
				String transnum = (String) rcv.checkString("transnum");

				if (!transnum.equals("")) {
					ret = css.findManuCost(" where transnum1='" + transnum
							+ "'");
					if (ret.size() > 0) {
						ManuCost mc = ((ManuCost) ret.get(0));
						spec = mc.getKaiMoSpec();
						plate = mc.getPlate();
						ssign = mc.getSsign();
						specType = parse.parseSpec(spec).sort();
						scheme = new Integer(gss.getFlow(spec).getSchemeId());
					}
				}
				Product p = new Product();
				p.setSpecType(specType);
				p.setFactory(factory.intValue());
				p.setScheme(scheme.intValue());
				p.setSpec(spec);
				p.setPlate(plate);
				p.setSsign(ssign);
				System.out.println("--------------start to get:" + p.getId());
				CacheManager cm = CacheManager.getInstance();
				CacheShell cs = cm.getCacheShell(cm.SIMILIARY_LIST_CACHE);
				CacheSimModel csm = (CacheSimModel) cs.getValue(p);
				if (csm.getSimList() != null && csm.getSimList().size() > 0) {
					osmList = csm.getSimList();
					System.out
							.println("-----------------------------get from cache:"
									+ osmList.size());
				}

				JSONObject json = new JSONObject();
				JsonConfig cfg = new JsonConfig();
				cfg.registerJsonValueProcessor(java.util.Date.class,
						new DateJsonValueProcessor());
				cfg.registerJsonValueProcessor(java.sql.Date.class,
						new DateJsonValueProcessor());
				cfg.registerJsonValueProcessor(java.lang.Float.class,
						new FloatJsonValueProcessor());
				json.put("totalProperty", new Integer(osmList.size()));

				JSONArray arr = JSONArray.fromObject(osmList.toArray(), cfg);
				json.put("root", arr);

				response.getWriter().print(json);
			} catch (GSException e) {
				System.out.println("GSException：" + e.getMessage());
			} catch (CSException e) {
				System.out.println("CSException is found in getSimiList:"
						+ e.getMessage());
			}

		}

		out.flush();
		out.close();
	}

	/**
	 * Initialization of the servlet. <br>
	 * 
	 * @throws ServletException
	 *             if an error occurs
	 */
	public void init() throws ServletException {
	}

}
